package com.kly.user.task.v2;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.UserWlmDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class RemoveRelationTask {

    private static Log logger = LogFactory.getLog(RemoveRelationTask.class);

    @Autowired
    private UserWlmDao userWlmDao;

    @NacosValue(value = "${clear.expired.relation.like:24}", autoRefreshed = true)
    private int likeExpireHour;

    @NacosValue(value = "${clear.expired.relation.pass:24}", autoRefreshed = true)
    private int passExpireHour;

    @NacosValue(value = "${clear.expired.relation.dislike:24}", autoRefreshed = true)
    private int dislikeExpireHour;


    @NacosValue(value = "${clear.expired.relation.wlm.not.matched:24}", autoRefreshed = true)
    private int wlmExpireHour;


    @NacosValue(value = "${clear.expired.relation.switch:false}", autoRefreshed = true)
    private boolean clearExpiredRelationSwitch;
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();


    @Scheduled(fixedDelay = 60000 * 30)
    public void run() {

        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        logger.info("==RemoveRelationTask start ==");
        if(!clearExpiredRelationSwitch){
            logger.info("==RemoveRelationTask start , switch not open==");
            return;
        }

        try {
            userWlmDao.clearLikeExpiredRelation(likeExpireHour * 60);
        } catch (Exception e) {
            logger.error("==RemoveRelationTask clearLikeExpiredRelation error ==", e);
        }

        try {
            userWlmDao.clearWLMExpiredRelation(likeExpireHour * 60 * 3);
        } catch (Exception e) {
            logger.error("==RemoveRelationTask clearWLMExpiredRelation error ==", e);
        }

        try {
            userWlmDao.clearWlmButNotMatchExpiredRelation(wlmExpireHour * 60);
        } catch (Exception e) {
            logger.error("==RemoveRelationTask clearWlmButNotMatchExpiredRelation error ==", e);
        }
        try {
            userWlmDao.clearDislikeExpiredRelation(dislikeExpireHour * 60);
        } catch (Exception e) {
            logger.error("==RemoveRelationTask clearDislikeExpiredRelation error ==", e);
        }

        try {
            userWlmDao.clearPassExpiredRelation(passExpireHour * 60);
        } catch (Exception e) {
            logger.error("==RemoveRelationTask clearPassExpiredRelation error ==", e);
        }

    }
}
